package com.byt.framlib.imagePager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Parcelable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.byt.framlib.R;
import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.basemvp.BasePresenter;
import com.byt.framlib.commonwidget.ViewPagerFixed;
import com.byt.framlib.commonwidget.selectordialog.dialog.DialogOnClickListener;
import com.byt.framlib.commonwidget.selectordialog.dialog.NormalAlertDialog;
import com.byt.framlib.compressorutils.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import uk.co.senab.photoview.PhotoView;


/**
 * 查看大图 glide
 * 使用直接调用startImagePagerActivity(Activity activity, List<String> imgUrls, int position)
 */
public class BigImagePagerActivity extends BaseActivity {
    public static final String INTENT_IMGURLS = "imgurls";
    public static final String INTENT_POSITION = "position";
    //    private List<View> guideViewList = new ArrayList<View>();
//    private LinearLayout guideGroup;
    private TextView tvNum;

    public static void startImagePagerActivity(Context context, List<String> imgUrls, int position) {
        Intent intent = new Intent(context, BigImagePagerActivity.class);
        intent.putStringArrayListExtra(INTENT_IMGURLS, new ArrayList<String>(imgUrls));
        intent.putExtra(INTENT_POSITION, position);
        context.startActivity(intent);
    }

    public static void startImagePagerActivity(Activity activity, List<String> imgUrls, int position) {
        Intent intent = new Intent(activity, BigImagePagerActivity.class);
        intent.putStringArrayListExtra(INTENT_IMGURLS, new ArrayList<>(imgUrls));
        intent.putExtra(INTENT_POSITION, position);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.stv_fadein,
                R.anim.stv_fadeout);
    }

    public static void startImagePagerActivity(Activity activity, String imgs) {
        List<String> imgUrls = new ArrayList<>();
        imgUrls.add(imgs);
        Intent intent = new Intent(activity, BigImagePagerActivity.class);
        intent.putStringArrayListExtra(INTENT_IMGURLS, new ArrayList<>(imgUrls));
        intent.putExtra(INTENT_POSITION, 0);
        activity.startActivity(intent);
        activity.overridePendingTransition(R.anim.stv_fadein,
                R.anim.stv_fadeout);
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BigImagePagerActivity.this.finish();
            BigImagePagerActivity.this.overridePendingTransition(R.anim.stv_fadein,
                    R.anim.stv_fadeout);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_image_pager;
    }

    @Override
    public BasePresenter initPreData() {
        return null;
    }

    @Override
    public void initView() {
        //设置透明状态栏
        ViewPager viewPager = (ViewPagerFixed) findViewById(R.id.pager);
//        guideGroup = (LinearLayout) findViewById(R.id.guideGroup);
        tvNum = findViewById(R.id.tv_page_num);
        int startPos = getIntent().getIntExtra(INTENT_POSITION, 0);
        ArrayList<String> imgUrls = getIntent().getStringArrayListExtra(INTENT_IMGURLS);
        ImageAdapter mAdapter = new ImageAdapter(this);
        mAdapter.setDatas(imgUrls);
        viewPager.setAdapter(mAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
//                for (int i = 0; i < guideViewList.size(); i++) {
//                    guideViewList.get(i).setSelected(i == position ? true : false);
//                }
                tvNum.setText((position + 1) + "/" + imgUrls.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setCurrentItem(startPos);
        tvNum.setText((startPos + 1) + "/" + imgUrls.size());
//        addGuideView(guideGroup, startPos, imgUrls);
    }

    /* private void addGuideView(LinearLayout guideGroup, int startPos, ArrayList<String> imgUrls) {
         if (imgUrls != null && imgUrls.size() > 0) {
             guideViewList.clear();
             for (int i = 0; i < imgUrls.size(); i++) {
                 View view = new View(this);
                 view.setBackgroundResource(R.drawable.selector_guide_bg);
                 view.setSelected(i == startPos ? true : false);
                 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.gudieview_width),
                         getResources().getDimensionPixelSize(R.dimen.gudieview_heigh));
                 layoutParams.setMargins(10, 0, 0, 0);
                 guideGroup.addView(view, layoutParams);
                 guideViewList.add(view);
             }
         }
     }*/
    private NormalAlertDialog normalAlertDialog;

    private class ImageAdapter extends PagerAdapter {

        private List<String> datas = new ArrayList<String>();
        private LayoutInflater inflater;
        private Context context;

        public void setDatas(List<String> datas) {
            if (datas != null)
                this.datas = datas;
        }

        public ImageAdapter(Context context) {
            this.context = context;
            this.inflater = LayoutInflater.from(context);

        }

        @Override
        public int getCount() {
            if (datas == null) return 0;
            return datas.size();
        }


        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = inflater.inflate(R.layout.item_pager_image, container, false);
            if (view != null) {
                final PhotoView imageView = (PhotoView) view.findViewById(R.id.image);
                //单击图片退出
                imageView.setOnPhotoTapListener((view1, x, y) -> {
                    BigImagePagerActivity.this.finish();
                    BigImagePagerActivity.this.overridePendingTransition(R.anim.act_fade_in_center,
                            R.anim.act_fade_out_center);
                });

                //loading
                final ProgressBar loading = new ProgressBar(context);
                FrameLayout.LayoutParams loadingLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                loadingLayoutParams.gravity = Gravity.CENTER;
                loading.setLayoutParams(loadingLayoutParams);
                ((FrameLayout) view).addView(loading);

                final String imgurl = datas.get(position);
                loading.setVisibility(View.VISIBLE);
                imageView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View v) {
                        showSaveDialog(imgurl);
                        return false;
                    }
                });
                Glide.with(context).load(imgurl)
                        .thumbnail(0.1f)
                        .error(R.drawable.ic_image_loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                loading.setVisibility(View.GONE);
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                loading.setVisibility(View.GONE);
                                return false;
                            }

                        })
                        .into(imageView);
                container.addView(view, 0);
            }
            return view;
        }

        private void showSaveDialog(String imgUrl) {
            normalAlertDialog = new NormalAlertDialog.Builder(mBContext)
                    .setButtonTextSize(14)
                    .setTitleVisible(true)
                    .setTitleText("保存图片")
                    .setTitleTextSize(16)
                    .setContentText("是否保存图片")
                    .setContentTextSize(14)
                    .setContentTextColor(R.color.color_272727)
                    .setOnclickListener(new DialogOnClickListener() {
                        @Override
                        public void clickLeftButton(View view) {

                        }

                        @Override
                        public void clickRightButton(View view) {
                            Observable.create(new ObservableOnSubscribe<File>() {
                                @Override
                                public void subscribe(ObservableEmitter<File> e) throws Exception {
                                    //通过gilde下载得到file文件,这里需要注意android.permission.INTERNET权限
                                    e.onNext(Glide.with(mBContext)
                                            .load(imgUrl)
                                            .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                                            .get());
                                    e.onComplete();
                                }
                            }).subscribeOn(Schedulers.io())
                                    .observeOn(Schedulers.newThread())
                                    .subscribe(new Consumer<File>() {
                                        @Override
                                        public void accept(File file) throws Exception {
                                            //第二个参数为你想要保存的目录名称
                                            String fileName = "staff-" + System.currentTimeMillis() + ".jpg";
                                            File destFile = new File(FileUtil.getPicDir(mBContext), fileName);
                                            //把gilde下载得到图片复制到定义好的目录中去
                                            copy(file, destFile);
                                            //保存图片后发送广播通知更新数据库
                                            Uri uri = Uri.fromFile(destFile);
                                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                                        }
                                    });
                            showShortToast("图片已保存在" + FileUtil.getPicDir(mBContext));

                        }
                    })
                    .build();
            normalAlertDialog.show();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        /**
         * 复制文件
         *
         * @param source 输入文件
         * @param target 输出文件
         */
        public void copy(File source, File target) {
            FileInputStream fileInputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                fileInputStream = new FileInputStream(source);
                fileOutputStream = new FileOutputStream(target);
                byte[] buffer = new byte[1024];
                while (fileInputStream.read(buffer) > 0) {
                    fileOutputStream.write(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fileInputStream.close();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}